package com.liang.pcc.chat;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class SessionService {

    private final StringRedisTemplate redisTemplate;

    // 创建新会话
    public String createSession(String userId, String modelType) {
        String sessionId = UUID.randomUUID().toString();
        Session session = Session.builder()
                .status("active")
                .title("新会话")
                .modelType(modelType)
                .sessionId(sessionId)
                .createTime(LocalDateTime.now())
                .build();
        redisTemplate.opsForHash().put("chat:session:" + userId, sessionId, JSON.toJSONString(session));
        return sessionId;
    }

    // 获取会话列表
    public List<Session> getSessionList(String userId) {
        if (Boolean.FALSE.equals(redisTemplate.hasKey("chat:session:" + userId))) {
            return List.of();
        }
        List<Session> sessionList = new ArrayList<>();
        redisTemplate.opsForHash().entries("chat:session:" + userId)
                .forEach((k, v) -> {
                    Session session = JSON.parseObject((String) v, Session.class);
                    sessionList.add(session);
                });
        // 根据创建时间降序排序
        return sessionList
                .stream()
                .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                .toList();
    }

    // 删除会话
    public void deleteSession(String userId, String sessionId) {
        redisTemplate.opsForHash().delete("chat:session:" + userId, sessionId);
    }

    public void updateSessionTitle(String userId, String sessionId, String title) {
        Session param = Session.builder()
                .status("active")
                .title(title)
                .modelType("deepseek-r1")
                .sessionId(sessionId)
                .createTime(LocalDateTime.now())
                .build();
        redisTemplate.opsForHash().put("chat:session:" + userId, sessionId, JSON.toJSONString(param));
    }
}